package com.qall.monitorability.actuator;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;

import com.qall.configability.prop.GetConfigUtil;
import com.qall.monitorability.entity.NodeEntity;
import com.qall.monitorability.service.NodeService;
import com.qall.util.*;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.EventListener;

import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Service
@Component
public class NodeInfoReportService {


    private static long SLEEP_TIME = 1000 * 60;
    private static String HEALTH_PATCH = "/actuator/health";
    private static String NAME_ENV_KEY = "spring.application.name";
    private static String NAMESPACE_ENV_KEY = "app.name-space";
    private static String HTTP_PORT_ENV_KEY = "server.port";

    @Reference(check = false, async = true)
    private NodeService nodeService;

    @EventListener
    public void run(ApplicationStartedEvent event) {

        String appName = event.getApplicationContext().getEnvironment().getProperty(NAME_ENV_KEY);
        String nameSpace = event.getApplicationContext().getEnvironment().getProperty(NAMESPACE_ENV_KEY);
        String serverPort = event.getApplicationContext().getEnvironment().getProperty(HTTP_PORT_ENV_KEY);

        Map<String, Object> stringStringMap = GetConfigUtil.getConfig(event.getSpringApplication());
        Map<String, Object> properties = ApplicationContextProviderUtils.getDefaultProperties();
        if (properties != null) {
            if (stringStringMap != null) {
                properties.putAll(stringStringMap);
            }
        } else {
            properties = stringStringMap;
        }
        String props = JSONUtil.toJson(properties);

        new Thread(() -> {
            while (true) {
                try {
                    String healthInfo = HttpUtil.get(HttpUtil.buildHttpRequest(MachineInfoUtil.getLocalIp(), Integer.parseInt(serverPort), HEALTH_PATCH), null);
                    NodeEntity nodeEntity = new NodeEntity().setAppName(appName).
                            setNameSpace(nameSpace).
                            setHealthInfo(healthInfo).
                            setCreateTime(DateUtil.FMyyyyMMddHHmmss.format(new Date())).
                            setUpdateTime(DateUtil.FMyyyyMMddHHmmss.format(new Date())).
                            setNodeIp(MachineInfoUtil.getLocalIp()).
                            setProperties(props);
                    LOGUtil.getLog().info("report node info to monitor center,node info is[{}]", JSONUtil.toJson(nodeEntity));
                    nodeService.reportNodeInfo(nodeEntity);
                    Thread.sleep(SLEEP_TIME);
                } catch (Exception e) {
                    LOGUtil.getLog().error(LOGUtil.getStackTraceInfo(e));
                }

            }

        }).start();
    }
}
